package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        //创建socket的同时,需要和服务器连接,告诉Socket服务器在哪里
        socket = new Socket(serverIp, serverPort);
    }

    public void start() {
        //tcp客户端和udp客户端都是差不多的
        //1.从控制台读取用户输入内容
        //2.把字符串作为请求,发送给服务器
        //3.从服务器上读取响应
        //4.把响应显示到界面上
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream();) {
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scannerNetWork = new Scanner(inputStream);
            while (true) {
                //1.
                System.out.println("-> ");
                String request = scanner.next();
                //2.
                printWriter.println(request);
                printWriter.flush();
                //3.
                String response = scannerNetWork.next();
                //4.
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9089);
        client.start();
    }
}
